<template>
    <div class="address-book" ref="addressBookRef" @scroll="handleScroll">
        <!-- 固钉显示的字母 -->
        <div v-if="stickyLetter" class="sticky-letter">{{ stickyLetter }}</div>
        <!-- 右侧字母导航 -->
        <template v-if="filterList().length">
            <div class="item-group" v-for="(group, index) in filterList()" :key="index">
                <div :class="['item-letter', { 'style': isFirstLetter }]" :id="group.letter">{{ group.letter }}</div>
                <div class="item-info" v-for="item in group.users" :key="item.id">
                    <ComAvatar isFirst :url="item.avatar ? item.avatar : ''" :name="item.initialLetter" :sex="item.sex" :size="22" />&nbsp;
                    <div class="name">
                        <div>{{ item.nickname }}</div>
                        <div class="email">
                            <span>{{ item.email }}</span>
                            <i class="EachApp EachApp_jian1" @click="handleBtn('add', item)"></i>
                        </div>
                    </div>
                </div>
            </div>
        </template>
        <a-empty v-else></a-empty>
    </div>
    <!-- 字母导航 -->
    <div class="letter-nav" @click="scrollToLetter">
        <span v-for="letter in filteredAlphabet" :key="letter">{{ letter }}</span>
    </div>
</template>

<script lang="ts" setup>
import * as Api from '@/api/common';
import { getPinYin } from '@/utils';
import type { UserInfoEntity } from '@/entity/UserEntity';
const emit = defineEmits(['addressBookOperate']);
const userList = ref([]);
const groupedUserList = ref<UserInfoEntity[]>([]);
const addressBookRef = ref<HTMLElement | null>(null);
const isManualScroll = ref(false);
const isFirstLetter = ref(true);
interface User {
  letter: string;
  nickname: string;
}
const pageParams = reactive({
    pageNum: 1,
    pageSize: 10,
    searchKey: '',
});
const stickyLetter = ref(''); // 固钉显示的字母
// 生成 A - Z 字母数组
const alphabet = Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i));

// 过滤后的字母数组
const filteredAlphabet = computed(() => {
    const existingLetters = groupedUserList.value.map(group => group.letter);
    return alphabet.filter(letter => existingLetters.includes(letter));
});

// 计算过滤后的数据
const filterList = computed(() => () => {
    const query = pageParams.searchKey?.trim().toLowerCase();
    if (query) {
        return groupedUserList.value.map(group => {
            const filteredUsers = group.users.filter((user: UserInfoEntity) => user.nickname?.toLowerCase().includes(query));
            return { ...group, users: filteredUsers };
        }).filter(group => group.users.length > 0);
    }
    return groupedUserList.value;
});


onMounted(() => {
    getList();
    window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
});

// 获取用户列表
const getList = async () => {
    try {
        const res = await Api.ApiUserList(pageParams);
        userList.value = res?.map((item: UserInfoEntity) => ({ ...item, letter: getPinYin(item.nickname as string)[0].toUpperCase() })) || [];
        userList.value.sort((a: User, b: User) => a.letter.localeCompare(b.letter));
        const grouped: Record<string, User[]> = {};
        userList.value.forEach((item: User) => {
            if (!grouped[item.letter]) {
                grouped[item.letter] = [];
            }
            grouped[item.letter].push(item);
        });
        groupedUserList.value = Object.keys(grouped).map((letter) => ({
            letter,
            users: grouped[letter]?.sort((a: User, b: User) => a.nickname?.localeCompare(b.nickname))
        }));
        console.log('userList.value===', groupedUserList.value);
    } catch (err) {
        console.log(err);
    }
};

// 滚动
const handleScroll = () => {
    if (isManualScroll.value) return;

    const itemLetters = document.querySelectorAll('.item-letter');
    let currentStickyLetter = '';

    itemLetters.forEach((letterElement, index) => {
        const rect = letterElement.getBoundingClientRect();
        if (rect.top - 120 <= 0) {
            if (index === itemLetters.length - 1 || itemLetters[index + 1].getBoundingClientRect().top > 120) {
                currentStickyLetter = letterElement.textContent as string;
            }
        }
    });

    stickyLetter.value = currentStickyLetter;
};

// 点击字母导航
const scrollToLetter = (e: MouseEvent) => {
        const target = e.target as HTMLElement;
    const targetLetter = target?.textContent;
    const targetElement = document.getElementById(targetLetter as string);
    if (targetElement) {
        isManualScroll.value = true;
        stickyLetter.value = targetLetter as string;
        targetElement.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
        const timer = setTimeout(() => {
            clearTimeout(timer);
            isManualScroll.value = false;
            isFirstLetter.value = false;
        }, 500);
    }
};

const handleBtn = (type: string, val: UserInfoEntity) => {
    if (type === 'add') {
        emit('addressBookOperate', val);
    }
};

defineExpose({
    pageParams
});
</script>

<style lang="scss" scoped>
.address-book {
    position: relative;
    padding: 0 15px 10px 15px;
    height: calc(100% - 115px);
    overflow-y: auto;
    .sticky-letter {
        position: sticky;
        top: 0;
        z-index: 1;
        background: #f2f2f2;
        // padding: 4px 0;
        color: #999;
    }
    .item-group {
        &:not(:last-child) {
            margin-bottom: 20px;
        }
        .item-letter {
            color: #999;
            // padding-bottom: 6px;
            &.style{
                scroll-margin-top: -15px; /* 与stickyHeight保持一致 */
            }
        }
        .item-info {
            display: flex;
            align-items: center;
            padding: 12px 12px 10px 12px;
            margin-top: -1px;
            border-radius: 4px;
            &:not(:last-child) {
                margin-bottom: 8px;
            }
            &:hover {
                cursor: pointer;
                background: #f5f7fa;
                .EachApp {
                    opacity: 1 !important;
                }
            }
            :deep(.arco-avatar) {
                width: 32px !important;
                height: 32px !important;
                font-size: 15px !important;
            }
            img {
                width: 30px;
                height: 30px;
            }
            .name {
                padding-left: 8px;
                font-size: 15px;
                flex: 1;
                .email {
                    color: #999;
                    font-size: 12px;
                    margin-top: 6px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    .EachApp {
                        opacity: 0;
                        font-size: 12px;
                        padding: 3px;
                        border-radius: 4px;
                        &:hover {
                            background: #ddd;
                        }
                    }
                }
            }
        }
    }
}
.letter-nav {
    position: absolute;
    top: 50%;
    right: 4px;
    transform: translateY(-50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    font-size: 11px;
    color: #999;
    cursor: pointer;
    z-index: 999;
    width: 20px;
    span {
        display: inline-flex;
        width: 100%;
        height: 18px;
        justify-content: center;
        align-items: center;
        transition: font-size 0.2s ease-in-out, padding-right 0.2s ease-in-out;
        &:hover {
            padding-right: 15px;
            font-size: 16px;
        }
    }
}
</style>
